<template>
  <div>
    <!-- 搜索栏 -->
    <el-form v-show="showSearch" :inline="true" :model="queryParams">
      <el-form-item label="名称:">
        <el-input v-model="queryParams.name" clearable placeholder="请输入课程名"
                  style="width: 150px" @input="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <svg-icon icon-file-name="white-search" style="color: #1abc9c"></svg-icon>
          搜索
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button :disabled="courseIdList.length === 0" icon="Delete" plain type="danger"
                   @click="handleBatchDelete">批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain type="primary" @click="courseDialogVisible = true; isEditing=false;">
          新增
        </el-button>
      </el-col>
      <refresh-and-hide @refresh="handleRefresh" @toggle-search="handleToggleSearch"/>
    </el-row>
    <div class="scroll-container">
      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="courseList" border @sort-change="handleSortChange"
                @selection-change="handleSelectionChange">
        <!-- 表格选择列 -->
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <!--缩略图-->
        <el-table-column align="center" label="课程封面" prop="courseImage" width="180">
          <template #default="scope">
            <el-image :lazy="true" :src="scope.row.courseImage" class="image-cover" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <!-- 课程名 -->
        <el-table-column align="center" label="课程名" prop="name" width="160"></el-table-column>
        <!-- 课程描述 -->
        <el-table-column align="center" label="课程描述" prop="description"></el-table-column>
        <!-- 课程学分 -->
        <el-table-column align="center" label="课程学分" prop="credits" sortable="custom" width="160">
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column align="center" label="创建时间" prop="createTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column align="center" label="更新时间" prop="updateTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column align="center" label="操作" width="220">
          <template #default="scope">
            <el-button class="sdf" link type="primary" @click="handleEdit(scope.row)">
              <svg-icon icon-file-name="edit"></svg-icon>
              编辑
            </el-button>
            <el-button class="sd" link type="danger" @click="handleDelete(scope.row.courseId)">
              <svg-icon icon-file-name="delete"></svg-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination v-if="total > 0" :limit="pagInfo.pageSize" :page="pagInfo.currentPage" :total="total"
                style="float: right;" @pagination="getCoursesList"
                @update_limit="pagInfo.pageSize = $event"
                @update_page="pagInfo.currentPage = $event"/>
    <el-dialog :title="GTitle" :visible.sync="courseDialogVisible" width="50%">
      <el-form ref="editForm" :model="courseInfoForm" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="课程名称" prop="name">
          <el-input v-model="courseInfoForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程描述" prop="description">
          <el-input v-model="courseInfoForm.description" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程学分" prop="credits">
          <el-input v-model="courseInfoForm.credits" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程封面图片" prop="courseImage">
          <ImageUpload ref="courseImage" :limit="1" @update-file-list="handleUpdateFileList"></ImageUpload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="courseDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="saveCourse">保存</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import refreshAndHide from "@/common/refreshAndHide.vue";
import Pagination from "@/common/pagination.vue";
import {addCourse, deleteCurse, deleteCurseOnList, getCourseList, updateCourse} from "@/apis/admin";
import ImageUpload from '@/common/ImageUpload.vue'

export default {
  // 组件注册，允许在模板中使用导入的组件
  components: {
    Pagination, // 分页组件
    refreshAndHide, // 刷新和隐藏组件
    ImageUpload // 图片上传组件
  },
  // 组件的响应数据对象
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 3, max: 100, message: '课程名称长度在 3 到 100 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入课程描述', trigger: 'blur' },
          { min: 10, max: 500, message: '课程描述长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        credits: [
          { required: true, message: '请输入课程学分', trigger: 'blur' },
          { type: 'number', message: '课程学分必须为数字值', trigger: 'blur' }
        ],
        courseImage: [
          { validator: this.validateImage, trigger: 'change' }
        ]
      },
      // 控制搜索表单显示的布尔值
      showSearch: true,
      // 搜索参数对象
      queryParams: {
        name: '' // 课程名
      },
      //分页信息
      pagInfo: {
        currentPage: 1,
        pageSize: 10
      },
      // 存储选中的课程ID列表
      courseIdList: [],
      // 存储课程列表的数组
      courseList: [],
      // 控制表格加载状态的布尔值
      loading: false,
      // 存储总课程数量的变量
      total: 0,

      isEditing: false, // 控制是否处于编辑状态
      courseDialogVisible: false, // 控制编辑对话框的显示
      courseInfoForm: { // 编辑表单的数据模型
        courseId: '',
        courseImage: '',
        name: '',
        description: '',
        credits: ''
      },
      formLabelWidth: '120px', // 表单标签宽度
    };
  },
  methods: {
    // 校验图片上传的自定义方法
    validateImage(rule, value, callback) {
      if (!value) {
        return callback(new Error('请上传课程封面图片'));
      }
      // 这里可以添加更多的图片校验逻辑，比如文件类型、大小等
      callback();
    },
    // 定义一个方法来接收子组件传递的 fileList,用于图片组件和该组件之间通信
    handleUpdateFileList(newFileList) {
      // 使用传递过来的 fileList 更新父组件的 parentFileList
      // 遍历 newFileList 数组
      newFileList.forEach(file => {
        // 将每个文件的 URL 添加到 imageUrls 数组中
        this.courseInfoForm.courseImage = file.url;
      });
    },
    // 处理编辑按钮点击事件
    handleEdit(data) {
      this.courseInfoForm = data;
      this.courseDialogVisible = true;
      this.isEditing = true;
      this.$nextTick(() => {
        this.$refs.courseImage.fileList = [];
        this.$refs.courseImage.setFileList(data.courseImage)
      })
    },
    // 更新课程信息
    saveCourse() {
      this.courseInfoForm.credits = Number(this.courseInfoForm.credits);
      if (this.isEditing){
        updateCourse(this.courseInfoForm).then(() => {
          this.$message.success("课程信息更新成功");
          this.courseDialogVisible = false; // 关闭对话框
          this.getCoursesList(); // 重新加载课程列表
        }).catch(error => {
          this.$message.error("更新课程信息失败");
        });
      } else {
        let data = {
          courseImage: this.courseInfoForm.courseImage,
          name: this.courseInfoForm.name,
          description: this.courseInfoForm.description,
          credits: this.courseInfoForm.credits
        }
        addCourse(data).then(() => {
          this.$message.success("课程信息添加成功");
          this.courseDialogVisible = false; // 关闭对话框
          this.getCoursesList(); // 重新加载课程列表
        }).catch(error => {
          this.$message.error("课程信息添加失败");
        });
      }
    },
    // 前端排序函数
    handleSortChange({prop, order}) {
      if (!order) {
        // 如果没有排序顺序，可能是恢复到未排序状态
        this.getCoursesList();
        return;
      }

      // 根据排序信息对 articleList 进行排序
      // articleList 是一个数组，包含要显示在表格中的文章
      this.courseList.sort((a, b) => {
        if (order === 'ascending') {
          return a[prop] - b[prop]; // 升序排序
        } else {
          return b[prop] - a[prop]; // 降序排序
        }
      });
    },
    // 处理搜索显示/隐藏的逻辑
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 处理刷新数据的逻辑
    handleRefresh() {
      this.getCoursesList();
      this.$message.success('列表已刷新');
    },
    // 搜索课程的方法
    handleQuery() {
      this.loading = true;
      // 重置当前页为第一页
      this.pagInfo.currentPage = 1;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = {
        name: this.queryParams.name,
        teacherName: this.queryParams.teacherName,
      }
      const DTOdata = {
        pagination,
        queryParams//只有搜索时才会带上
      }
      getCourseList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((article) => {
            article.createTime = this.$common.dateFormat(article.createTime);
            article.endTime = this.$common.dateFormat(article.endTime);
            article.updateTime = this.$common.dateFormat(article.updateTime);
          });
          this.courseList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    // 处理表格行选择事件
    handleSelectionChange(selection) {
      this.courseIdList = selection.map(item => item.courseId);
    },
    //批量删除方法
    handleBatchDelete() {
      if (this.courseIdList.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要删除的课程'
        });
        return;
      }
      // 确认弹窗
      this.$confirm('确定要删除选中的课程吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: this.courseIdList
        }
        deleteCurseOnList(data).then(res => {
          if (res.data.code === 1) {
            this.$message.success("删除课程成功");
            this.getCoursesList();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除单个课程的方法
    handleDelete(id) {
      if (id) {
        this.$confirm('确定要删除该文章吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const commonSetDTOdata = {
            courseId: id,
          }
          // 这里应该是一个API请求，删除文章
          deleteCurse(commonSetDTOdata).then(res => {
            if (res.data.code === 1) {
              this.$message.success("删除课程成功");
              this.getCoursesList();
            }
          }).catch(error => {
            this.$message.error("删除课程信息失败");
          });

        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消删除'
          });
        });
      }
    },
    // 获取课程列表的方法
    async getCoursesList() {
      this.loading = true;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = null;
      const DTOdata = {
        pagination,
        queryParams
      }
      await getCourseList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((course) => {
            course.createTime = this.$common.dateFormat(course.createTime);
            course.updateTime = this.$common.dateFormat(course.updateTime);
            course.endTime = this.$common.dateFormat(course.endTime);
          });
          this.courseList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    }
  },
  created() {
    this.getCoursesList();
  },
  computed:{
    GTitle() {
      return this.isEditing ? '编辑课程' : '新增课程'
    }
  }
};
</script>

<style scoped>

.scroll-container {
  max-height: 646px; /* 您可以根据需要调整这个值 */
  overflow-y: auto;
}

.sdf {
  background: transparent;
  border-color: transparent;
  color: #76d7ff;
}

.sd {
  background: transparent;
  border-color: transparent;
  color: #fa1224;
}

.image-cover {
  width: 100px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;

  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
  }
}

.time {
  display: flex;
  align-items: center;
}
</style>

